package com.sun.mybatisplus.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 根据传递的Bean的名称和类型到IOC容器中查询对应的bean对象
 */

public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }


    /**
     * 根据名称获取bean
     * @param name
     * @return
     */
    public Object getBean(String name) {
        return applicationContext.getBean(name);
    }


    /**
     * 根据类型查询bean对象
     * @param requiredType
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }


    /**
     * 根据类型和名称查询bean对象
     * @param requiredType
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> requiredType,String name){
        return applicationContext.getBean(name,requiredType);
    }


    /**
     * 判断bean是否存在
     * @param name
     * @return
     */
    public static boolean containsBean(String name){
        return applicationContext.containsBean(name);
    }


    /**
     * 判断bean是否是单例的
     * @param name
     * @return
     */
    public static Class<? extends Object> getType(String name){
       return applicationContext.getType(name);
    }
}
